{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9225133e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "EPSILON = 1e-5\n",
    "N=4096"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "e9c2ae88",
   "metadata": {},
   "outputs": [],
   "source": [
    "def gcc_phat(x1,x2):\n",
    "    xf1 = np.fft.fft(x1)\n",
    "    xf2 = np.fft.fft(x2)\n",
    "\n",
    "    G = xf1 * np.conj(xf2)\n",
    "    print(G)\n",
    "    W = 1.0/(np.abs(G) + EPSILON)\n",
    "    print(W)\n",
    "    GW = G*W\n",
    "\n",
    "    R12 = np.fft.ifft(GW)\n",
    "    R12_shift = np.fft.fftshift(R12)\n",
    "\n",
    "    return R12_shift"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "f1164e65",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 输入信号，假定sig_a为左侧硅麦输入，sig_b为右侧硅麦输入\n",
    "# sig_b迟于sig_a 2048个采样点\n",
    "sig_a = np.random.randn(N)\n",
    "sig_b = np.append(np.random.randn(N//2)*1,sig_a[:N//2]*0.9+np.random.randn(N//2)*0.1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "0ab7ca02",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 4860.97587415   +0.j          1505.21659561-1390.54331102j\n",
      "  2036.91337872+4256.51264239j ... -1665.96081351-1171.5276921j\n",
      "  2036.91337872-4256.51264239j  1505.21659561+1390.54331102j]\n",
      "[0.00020572 0.00048799 0.00021192 ... 0.000491   0.00021192 0.00048799]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "np.int64(3803)"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.abs(gcc_phat(sig_a,sig_b))[1:].argmax()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
